<template>
  <div class="dataCleaning">
    <el-row :gutter="20" style="height: 100%">
      <el-col :span="12">
        <div class="grid-content-wrapper">
          <div class="grid-content">
            <h4 class="header_1 header-border">配置</h4>
            <div class="cleaningWay">
              <div class="title">数据来源</div>
              <el-select v-model="dataSelected" style="width: 100%">
                <el-option
                  v-for="item in selectedData"
                  :key="item"
                  :label="item"
                  :value="item"
                  >{{ item }}</el-option
                >
              </el-select>
            </div>
            <div class="cleaningWay">
              <div class="title">选择文件</div>
              <div class="select-switch-box">
                <el-select
                  v-model="selectedFile"
                  placeholder="请选择文件"
                  :disabled="!dataSelected"
                  @change="handleFileSelection"
                >
                  <el-option
                    v-for="file in computedFileList"
                    :key="file.id"
                    :label="file.label"
                    :value="file.path"
                  />
                </el-select>
              </div>
            </div>
            <div class="cleaningWay">
              <div class="title">清洗方式</div>
              <div class="select-switch-box">
                <el-select
                  v-model="selectValue.selectA"
                  :disabled="!switchValueArr[0].value"
                >
                  <el-option
                    v-for="item in cleaningWay_options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <el-switch
                  v-model="switchValueArr[0].value"
                  style="margin-left: 20px"
                  @change="switchChangeA"
                />
              </div>
            </div>
            <div class="cleaningWay">
              <div class="title">降维方法</div>
              <div class="select-switch-box">
                <el-select
                  v-model="selectValue.selectB"
                  :disabled="!switchValueArr[1].value"
                >
                  <el-option
                    v-for="item in dimenredu_options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <el-switch
                  v-model="switchValueArr[1].value"
                  style="margin-left: 20px"
                  @change="switchChangeB"
                />
              </div>
            </div>
            <div class="cleaningWay">
              <div class="title">融合方法</div>
              <div class="select-switch-box">
                <el-select
                  v-model="selectValue.selectC"
                  :disabled="!switchValueArr[2].value"
                >
                  <el-option
                    v-for="item in fuseWay_options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <el-switch
                  v-model="switchValueArr[2].value"
                  style="margin-left: 20px"
                  @change="switchChangeC"
                />
              </div>
            </div>
            <div class="cleaningWay">
              <div class="title">估计方法</div>
              <div class="select-switch-box">
                <el-select
                  v-model="selectValue.selectD"
                  :disabled="!switchValueArr[3].value"
                >
                  <el-option
                    v-for="item in estimateWay_options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <el-switch
                  v-model="switchValueArr[3].value"
                  style="margin-left: 20px"
                  @change="switchChangeD"
                />
              </div>
            </div>
          </div>
          <div class="btns">
            <el-button
              type="primary"
              style="padding: 10px 40px"
              @click="startClick"
              >开始处理</el-button
            >
          </div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="grid-content-wrapper">
          <div class="grid-content ep-bg-purple">
            <h4 class="header_1">处理状态</h4>
            <div class="over_btn">
              <el-tag
                :type="tagType"
                style="width: 90%; padding: 15px 0; font-size: 18px"
              >
                {{ c_status }}
              </el-tag>
            </div>
            <div class="component-main">
              <div v-if="isLoading" class="loading-container">
                <div class="spinner" />
                <p>数据处理中，请稍候...</p>
              </div>
              <component
                :is="component"
                v-else
                ref="handleChildRef"
                :fileData="downloadedZip"
                :fileName="fileName"
                :selectValue="selectValue"
                :switchValue="switchValueArr"
                :currentDevice="dataSelected"
                @childTitleStatusClick="chartTitleStatus"
              />
            </div>
          </div>
          <div class="btns">
            <el-button
              v-show="labelArr.length > 1"
              type="primary"
              style="padding: 10px 40px"
              :disabled="clickNum === 0"
              @click="goBack"
              >上一个</el-button
            >
            <el-button
              v-show="labelArr.length > 1"
              type="primary"
              style="padding: 10px 40px"
              :disabled="clickNum === labelArr.length - 1"
              @click="goOnClick"
              >{{ goOnBtnText }}</el-button
            >
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, shallowRef, nextTick, watch } from "vue";
import { codeList } from "@/api/dataProcessing";
import { fetchFileList, downloadFileFromDataLake } from "@/api/dataProcessing";
import { message } from "@/utils/message";
import { genFileId } from "element-plus";
import {
  chartA,
  chartB,
  chartC,
  chartD
  // lf,
} from "./dataChart";
import JSZip from "jszip";
const goOnBtnText = ref("继续");
const selectedData = ref([]);
const handleChildRef = ref(null);
const dataSelected = ref(null);
let c_status = ref("未清洗");
let switchValueArr = ref([
  {
    value: false,
    label: "chartA"
  },
  {
    value: false,
    label: "chartB"
  },
  {
    value: false,
    label: "chartC"
  },
  {
    value: false,
    label: "chartD"
  }
]);
const selectValue = ref({
  selectA: 1,
  selectB: "LLE",
  selectC: 0,
  selectD: 0
});
const cleaningWay_options = [
  {
    value: 1,
    label: "缺失值填充"
  },
  {
    value: 0,
    label: "重复值删除"
  }
];
const dimenredu_options = [
  {
    value: "PCA",
    label: "主成成分分析(PCA)"
  },
  {
    value: "LLE",
    label: "局部线性嵌入式降维(LLE)"
  }
];
const fuseWay_options = [
  {
    value: 0,
    label: "卡尔曼滤波"
  },
  {
    value: 1,
    label: "频谱分析"
  }
];
const estimateWay_options = [
  {
    value: 0,
    label: "卷积神经网络(CNN)"
  },
  {
    value: 1,
    label: "残差神经网络(Res_net)"
  }
];
const component = shallowRef();
const componentList = shallowRef([
  {
    key: "chartA",
    name: "数据清洗",
    show: true,
    component: chartA
  },
  {
    key: "chartB",
    name: "数据降维",
    show: true,
    component: chartB
  },
  {
    key: "chartC",
    name: "数据融合",
    show: true,
    component: chartC
  },
  {
    key: "chartD",
    name: "数据估计",
    show: true,
    component: chartD
  }
  // {
  //   key: "lf",
  //   name: "本体实例",
  //   show: true,
  //   component: lf
  // },
]);
const statusCode = ref(null);
const chartTitleStatus = item => {
  c_status.value = item.title;
  statusCode.value = item.status;
};
onMounted(() => {
  getSelectedList();
  getFileList();
});
watch(dataSelected, (newVal, oldVal) => {
  if (newVal !== oldVal) {
    selectedFile.value = null; // 清空文件选择
  }
});

const downloadedFile = ref(null); // 存储下载的文件对象
const downloadedZip = ref(null); // 存储更改后的 JSON 文件对象
const fileName = ref(""); // 存储文件名
const selectedFile = ref(""); // 存储选中的文件名
const fileList = ref([]); // 文件列表
//下载接口
const handleFileSelection = () => {
  if (selectedFile.value) {
    downloadFile(selectedFile.value)
      .then(() => {
        // 强制通知组件更新
        nextTick(() => {});
      })
      .catch(error => {
        console.error("下载文件失败", error);
      });
  }
};
let isFileReady = false; // 用于表示文件是否准备好
let downloadId = ref(null); // 使用 ref 来使 downloadId 响应式
let downloadVersion = ref(0); // 用于表示文件的下载版本，每次下载增加
let currentDownloadVersion = ref(0); // 当前正在下载处理的文件版本号
const downloadFile = async path => {
  try {
    const data = {
      path: path
    };
    const file = await downloadFileFromDataLake(data);
    downloadedFile.value = file;
    fileName.value = file.name;
    console.log("下载的文件对象：", downloadedFile.value);
    // // 生成唯一标识符，时间戳也可以作为标识符
    // downloadId.value = Math.floor(new Date().getTime() / 10000000); // 使用秒级时间戳
    // console.log("时间戳：", downloadId.value);
    // 增加下载版本号

    const reader = new FileReader();
    reader.onload = function (event) {
      const fileContent = event.target.result;
    };
    reader.readAsText(downloadedFile.value);
    // 使用 JSZip 解压 ZIP 文件
    const arrayBuffer = await downloadedFile.value.arrayBuffer();
    const zip = await JSZip.loadAsync(arrayBuffer);

    // 遍历 ZIP 文件中的内容
    for (const relativePath in zip.files) {
      const zipEntry = zip.files[relativePath];
      if (!zipEntry.dir) {
        const fileContent = await zipEntry.async("string"); // 读取文件内容为字符串
        console.log(`解压后的文件内容 (${relativePath})：`, fileContent);

        // 将文件扩展名从 .txt 更改为 .json
        const jsonFileName = relativePath.replace(".txt", ".csv");

        // 创建新的 File 对象，内容保持不变
        const jsonFile = new File([fileContent], jsonFileName, {
          type: "application/json"
        });

        // 存储到新的变量 downloadedZip
        downloadedZip.value = jsonFile;
        console.log("新的 csv 文件对象：", downloadedZip.value);
        // 设置标志位为 true
        isFileReady = true;
        message("下载文件完成", { type: "success" });
      }
    }
    // // 增加下载版本号
    // downloadVersion.value += 1; // 每次下载时增加版本号
    // currentDownloadVersion.value = downloadVersion.value; // 更新当前下载版本
    // console.log("当前下载版本：", currentDownloadVersion.value); // 打印当前版本
  } catch (error) {
    console.error("下载文件失败", error);
    // 在此处理错误，例如向用户显示错误消息
    message("下载文件失败，请重试", { type: "error" });
  }
};

const computedFileList = computed(() => {
  if (!dataSelected.value) {
    // 如果 dataSelected 为空，返回原始的 fileList，label 使用 file.path
    return fileList.value.map(file => ({
      id: file.id,
      path: file.path,
      label: file.path // 显示的标签为原始文件名
    }));
  }
  return fileList.value.map(file => ({
    id: file.id,
    path: file.path, // 原始的文件路径，用于 value
    label: `${file.path} ${dataSelected.value}` // 修改后的标签，用于显示
  }));
});

// 获取文件列表函数
const getFileList = async () => {
  const queryParams = {
    path: "hdfs://10.8.58.1:8020/testdata/0" // 保持与 Postman 中一致
  };

  try {
    // 发送请求获取文件列表，传递整个对象而不是字符串
    const result = await fetchFileList(queryParams);

    if (result && result.data) {
      console.log("Received file list data:", result.data.data.data);
      fileList.value = result.data.data.data; // 将 data 数组赋值给 fileList
    } else {
      console.error("未收到文件列表数据");
    }
  } catch (error) {
    console.error("获取文件列表失败:", error.message); // 打印错误信息
    if (error.response) {
      // 如果有响应，打印响应状态和数据
      console.error("Error response status:", error.response.status);
      console.error("Error response data:", error.response.data);
    } else if (error.request) {
      // 如果没有响应，打印请求信息
      console.error("No response received, request details:", error.request);
    } else {
      // 其他错误
      console.error("Error setting up request:", error.message);
    }
  }
};

let labelArr = ref([]);

// 开始处理
// 添加一个加载状态变量
const isLoading = ref(false); // 是否正在加载

// 开始处理
const startClick = () => {
  if (
    !switchValueArr.value[0].value &&
    !switchValueArr.value[1].value &&
    !switchValueArr.value[2].value &&
    !switchValueArr.value[3].value
  ) {
    message("未选中算法", { type: "error" });
    return;
  }

  if (!dataSelected.value) {
    message("请选择数据来源", { type: "error" });
    return;
  }
  if (!selectedFile.value) {
    message("请选择文件", { type: "error" });
    return;
  }
  if (!downloadedZip.value) {
    message("文件未下载完成", { type: "error" });
    return;
  }
  // 确保是最新下载的文件
  // // 确保是最新下载的文件
  // if (!isFileReady || downloadVersion.value !== currentDownloadVersion.value) {
  //   message("请先下载并解压最新文件", { type: "error" });
  //   return;
  // }
  clickNum.value = 0;
  tagType.value = "primary";

  // 清空组件
  component.value = null;
  goOnBtnText.value = "继续";
  labelArr.value = switchValueArr.value.filter(item => {
    return item.value === true;
  });

  // 设置加载状态为 true
  isLoading.value = true;

  // 模拟数据处理，延迟显示组件
  setTimeout(() => {
    component.value = null;
    componentList.value.filter(item => {
      if (item.key == labelArr.value[0].label) {
        component.value = item.component;
      }
    });

    // 数据处理完成，设置加载状态为 false
    isLoading.value = false;

    nextTick(() => {
      handleChildRef.value.childMethod();
    });
  }, 300); // 使用延迟模拟返回数据
};

// 继续
let clickNum = ref(0);
const goOnClick = () => {
  if (
    !switchValueArr.value[0].value &&
    !switchValueArr.value[1].value &&
    !switchValueArr.value[2].value &&
    !switchValueArr.value[3].value
  ) {
    message("未选中算法", { type: "error" });
    return;
  }
  if (!selectedFile.value) {
    message("请选择文件", { type: "error" });
    return;
  }
  labelArr.value = switchValueArr.value.filter(item => item.value === true);

  if (clickNum.value < labelArr.value.length - 1) {
    clickNum.value++;
    // 清空组件
    component.value = null;

    setTimeout(() => {
      componentList.value.filter(item => {
        if (item.key == labelArr.value[clickNum.value].label) {
          component.value = item.component;
        }
      });
      nextTick(() => {
        handleChildRef.value.childMethod();
      });
    }, 300); // 模拟数据处理延迟
  }

  if (c_status.value === "主轴转速异常") {
    tagType.value = "danger";
  }
  if (clickNum.value === labelArr.value.length - 1) {
    goOnBtnText.value = "完成";
  }
};

// 上一个
const goBack = () => {
  if (clickNum.value > 0) {
    goOnBtnText.value = "继续";
    clickNum.value--;
    // 清空组件
    component.value = null;

    setTimeout(() => {
      componentList.value.filter(item => {
        if (item.key == labelArr.value[clickNum.value].label) {
          component.value = item.component;
        }
      });
      nextTick(() => {
        handleChildRef.value.childMethod();
      });
    }, 300); // 模拟数据处理延迟
  }
};

// 获取数据来源
const getSelectedList = () => {
  codeList()
    .then(res => {
      if (res.status === 200) {
        console.log(res.data); // 打印数据
        selectedData.value = res.data;
        console.log(selectedData.value); // 打印更新后的 selectedData
      }
    })
    .catch(error => {
      console.log(error);
    });
};

const switchChangeA = value => {
  switchValueArr.value[0].value = value;
};
const switchChangeB = value => {
  if (switchValueArr.value[2].value) {
    message("已选择融合", { type: "error" });
    switchValueArr.value[1].value = false;
    return;
  }
  switchValueArr.value[1].value = value;
};
const switchChangeC = value => {
  if (switchValueArr.value[1].value) {
    message("已选择降维", { type: "error" });
    switchValueArr.value[2].value = false;
    return;
  }
  switchValueArr.value[2].value = value;
};
const switchChangeD = value => {
  switchValueArr.value[3].value = value;
};
// const switchChangeUp = (value) => {
//   switchValueUp.value = value;
// }

let fileRef = ref();
const base64File = ref("");
// 选择文件时被调用，将他赋值给fileRef
const handleChange = file => {
  fileRef.value = file.raw;
  fileName.value = file.name;
  const reader = new FileReader();
  reader.onload = e => {
    base64File.value = e.target.result;
  };
  reader.readAsDataURL(fileRef.value);
};

// 覆盖前一个选择的
const handleExceed = files => {
  fileRef.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  fileRef.value.handleStart(file);
};

//计算属性
const tagType = computed(() => {
  // if (c_status.value ==='未清洗') {
  //     return 'danger'
  // }
  // else if (c_status.value ==='清洗完成') {
  //   return 'success'
  //   }
});
</script>

<style lang="scss" scoped>
.dataCleaning {
  width: 100%;
  height: 100%;
  font-size: 16px;

  .grid-content-wrapper {
    height: 100%;
    border-radius: 10px;
    box-shadow: 2px 2px 2px 1px rgba(0, 0, 0, 0.2);
    background-color: #fff;
    margin-bottom: 0px;
    padding: 0 10px;
    display: flex;
    flex-flow: column;
    justify-content: space-between;
  }

  .grid-content {
    flex: 1;
  }

  .header_1,
  .header_2 {
    width: 100%;
    height: 48px;
    line-height: 48px;
    padding-left: 20px;
  }

  .header-border {
    border-bottom: 1px solid #ccc;
  }

  .title {
    font-size: 15px;
  }
  .fileSelection {
    width: 100%;
    line-height: 40px;
    padding-left: 20px;
    margin-top: 10px;
    display: block;
  }

  .cleaningWay,
  .storePath {
    width: 100%;
    line-height: 40px;
    padding-left: 20px;
    margin-top: 10px;
  }

  .select-switch-box {
    display: flex;
  }

  .btns {
    width: 100%;
    text-align: right;
    padding: 0 20px 20px 0;
  }

  .over_btn {
    text-align: center;
    width: 100%;
    margin-bottom: 20px;
  }

  .chart {
    width: 100%;
    height: 430px;
    margin-top: 20px;
  }
  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 300px; /* 根据你的需求调整高度 */
  }

  .spinner {
    width: 50px;
    height: 50px;
    border: 5px solid rgba(0, 0, 0, 0.1);
    border-top-color: #007bff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
}
</style>
